package io.adrainty.bolee.security.service.impl;

import io.adrainty.bolee.framework.commons.basic.ResponseCode;
import io.adrainty.bolee.framework.commons.exception.AppException;
import io.adrainty.bolee.security.models.constants.CompanyConstants;
import io.adrainty.bolee.security.models.entity.CompanyEntity;
import io.adrainty.bolee.security.repository.ICompanyRepository;
import io.adrainty.bolee.security.service.ICompanyService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>CompanyServiceImpl</p>
 *
 * @author AdRainty
 * @version V1.0.0
 * @description ICompanyService
 * @since 2025/8/1 14:21:28
 */

@Slf4j
@Service
public class CompanyServiceImpl implements ICompanyService {

    @Resource
    private ICompanyRepository companyRepository;

    @Override
    public boolean refreshCompanyWebsiteCache() {
        List<CompanyEntity> companyBOList = companyRepository.listValidateCompany();
        for (CompanyEntity companyEntity : companyBOList) {
            log.info("RefreshCompanyCache, companyId: {}", companyEntity.getCompanyNo());
            companyRepository.refreshCompanyWebsiteCache(companyEntity);
        }
        return true;
    }

    @Override
    @Transactional
    @Caching(
            evict = {
                    @CacheEvict(value = CompanyConstants.COMPANY_LIST_KEY, allEntries = true),
                    @CacheEvict(value = CompanyConstants.COMPANY_PAGE_KEY, allEntries = true)
            },
            put = {
                    @CachePut(value = CompanyConstants.COMPANY_BASIC_CACHE_KEY, key = "#result.id")
            }
    )
    public CompanyEntity createCompany(CompanyEntity companyEntity) {
        CompanyEntity result = companyRepository.createCompany(companyEntity);
        if (result == null) {
            throw new AppException(ResponseCode.COMPANY_CREATE_ERROR);
        }

        companyRepository.refreshCompanyWebsiteCache(result);
        return result;
    }

    @Override
    public CompanyEntity findCompanyEntity(String companyNo) {
        return companyRepository.findCompanyEntity(companyNo);
    }

}
